package cn.biao.epic.sys.modular.system.service;

import cn.biao.epic.base.auth.context.LoginContextHolder;
import cn.biao.epic.base.auth.model.LoginUser;
import cn.biao.epic.base.pojo.page.AntdPageFactory;
import cn.biao.epic.core.util.ToolUtil;
import cn.biao.epic.model.exception.ServiceException;
import cn.biao.epic.sys.core.constant.Const;
import cn.biao.epic.sys.core.constant.factory.ConstantFactory;
import cn.biao.epic.sys.core.constant.state.ManagerStatus;
import cn.biao.epic.sys.core.exception.enums.BizExceptionEnum;
import cn.biao.epic.sys.core.util.SaltUtil;
import cn.biao.epic.sys.modular.system.entity.User;
import cn.biao.epic.sys.modular.system.entity.UserPos;
import cn.biao.epic.sys.modular.system.factory.UserFactory;
import cn.biao.epic.sys.modular.system.mapper.UserMapper;
import cn.biao.epic.sys.modular.system.model.UserDto;
import cn.hutool.core.collection.CollectionUtil;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import java.util.Arrays;
import java.util.HashMap;
import java.util.Map;

/**
 * @Auther Uncle_Z
 * @date 2019/12/6 18:05
 * @Email:2545375@qq.com
 * @Descrition
 */
@Service
public class UserService extends ServiceImpl<UserMapper, User> {

    @Autowired
    private MenuService menuService;

    @Autowired
    private UserPosService userPosService;

    /**
     * 刷新当前登录用户的信息
     *
     * @author fengshuonan
     * @Date 2019/1/19 5:59 PM
     */
    public void refreshCurrentUser() {
        //TODO 刷新
    }

    /**
     * 添加
     *
     * @author uncle_z
     * @Date 2019/12/10 17:42
     * @Param [user]
     * @File UserService.java
     */
    @Transactional(rollbackFor = Exception.class)
    public void addUser(UserDto user) {
        User thenUser = this.getByAccount(user.getAccount());
        if (thenUser != null) {
            throw new ServiceException(BizExceptionEnum.USER_ALREADY_REG);
        }
        String salt = SaltUtil.getRandomSalt();
        String password = SaltUtil.md5Encrypt(user.getPassword(), salt);

        User newUser = UserFactory.createUser(user, password, salt);
        this.save(newUser);
    }

    /**
     * 修改用户
     *
     * @author uncle_z
     * @Date 2019/12/11 11:01
     * @Param [userDto]
     * @File UserService.java
     */
    @Transactional(rollbackFor = Exception.class)
    public void editUser(UserDto userDto) {
        User oldUser = getById(userDto.getUserId());
        if (LoginContextHolder.getContext().hasRole(Const.ADMIN_NAME)) {
            this.updateById(UserFactory.editUser(userDto, oldUser));
        } else {
            LoginUser loginUser = LoginContextHolder.getContext().getUser();
            if (loginUser.getId().equals(userDto.getUserId())) {
                updateById(UserFactory.editUser(userDto, oldUser));
            } else {
                throw new ServiceException(BizExceptionEnum.NO_PERMITION);
            }
        }
    }

    /**
     * 删除用户
     *
     * @author uncle_z
     * @Date 2019/12/11 11:01
     * @Param [userId]
     * @File UserService.java
     */
    @Transactional(rollbackFor = Exception.class)
    public void deleteUser(Long userId) {
        if (userId.equals(Const.ADMIN_ID)) {
            throw new ServiceException(BizExceptionEnum.CANT_DELETE_ADMIN);
        }

        this.setStatus(userId, ManagerStatus.DELETED.getCode());
    }

    /**
     * 修改用户状态
     *
     * @author uncle_z
     * @Date 2019/12/11 11:00
     * @Param [userId, status]
     * @File UserService.java
     */
    public int setStatus(Long userId, String status) {
        return baseMapper.setState(userId, status);
    }

    /**
     * 通过账号获取用户
     */
    public User getByAccount(String account) {
        return baseMapper.selectByAccount(account);
    }

    /**
     * 修改密码
     *
     * @author uncle_z
     * @Date 2019/12/11 11:03
     * @Param [oldPassword, newPasswprd]
     * @File UserService.java
     */
    public void changePwd(String oldPassword, String newPasswprd) {
        Long userId = LoginContextHolder.getContext().getUserId();
        User user = getById(userId);
        String oldMd5 = SaltUtil.md5Encrypt(oldPassword, user.getSalt());
        if (user.getPassword().equals(oldMd5)) {
            String newMd5 = SaltUtil.md5Encrypt(newPasswprd, user.getSalt());
            user.setPassword(newMd5);
            updateById(user);
        } else {
            throw new ServiceException(BizExceptionEnum.OLD_PWD_NOT_RIGHT);
        }
    }

    /**
     *
     * 根据条件查询列表
     *
     * @author uncle_z
     * @Date 2019/12/11 11:12
     * @Param [name, beginTime, endTime]
     * @File UserService.java
     */
    public Page<Map<String, Object>> selectUsers(String name, String beginTime, String endTime) {
        Page page = AntdPageFactory.defaultPage();
        return baseMapper.selectUsers(page, name, beginTime, endTime);
    }

    /**
     *
     * 设置用户的角色
     *
     * @author uncle_z
     * @Date 2019/12/11 11:13
     * @Param [userId, roleIds]
     * @File UserService.java
     */
    public int setRoles(Long userId, String roleIds) {
        return baseMapper.setRoles(userId, roleIds);
    }

    /**
     *
     * 获取用户的基本信息
     *
     * @author uncle_z
     * @Date 2019/12/11 11:16
     * @Param [userId]
     * @File UserService.java
     */
    public Map<String, Object> getUserInfo(Long userId) {
        User user = getById(userId);
        Map<String, Object> map = UserFactory.removeUnSafeFields(user);

        HashMap<String,Object> allMap = CollectionUtil.newHashMap();
        allMap.putAll(map);
        allMap.put("roleName", ConstantFactory.me().getRoleName(user.getRoleId()));
        allMap.put("deptName", ConstantFactory.me().getDeptName(user.getDeptId()));
        return allMap;
    }
    /**
     * 判断当前登录的用户是否有操作这个用户的权限
     *
     * @author uncle_z
     * @Date 2019/12/11 10:50
     * @Param [userId]
     * @File UserService.java
     */
    public void assertAuth(Long userId) {

    }

    /**
     * 
     * 添加职位关联
     *
     * @author uncle_z
     * @Date 2019/12/11 11:24
     * @Param [positions, userId]
     * @File UserService.java 
     */
    private void addPosition(String positions, Long userId){
        if (ToolUtil.isNotEmpty(positions)) {
            String[] arrpos=positions.split(",");
            Arrays.stream(arrpos).forEach(v ->{
                UserPos userPos = new UserPos();
                userPos.setUserId(userId);
                userPos.setPosId(Long.valueOf(v));
                userPosService.save(userPos);
            });
        }
    }
}
